﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;

using Hasiu.Entity;

namespace Hasiu.Service
{
    public class NewsService
    {
        public static readonly NewsService _ = new NewsService();

        private ISession Session { get; set; }

        public NewsService()
        {
            Session = NHibernateHelper.GetCurrentSession();
        }

        public void Save(News news)
        {
            Session.Clear();
            Session.Save(news);
            Session.Flush();
        }

        public void Update(News news)
        {
            Session.Clear();
            Session.Update(news);
            Session.Flush();
        }

        public void Delete(params string[] id)
        {
            Session.Clear();
            var query = Session.Query<News>().Where(o => id.Contains(o.Id));
            foreach (var v in query)
            {
                Session.Delete(v);
            }
            Session.Flush();
        }

        public News Get(string id)
        {
            return Session.Get<News>(id);
        }

        public IList<News> GetList(
            int pageIndex,
            int pageSize,
            out int dataCount,
            string title,
            string newsType,
            DateTime? startTime,
            DateTime? endTime)
        {
            var queryCount = Session.CreateCriteria(typeof(News));
            var queryList = Session.CreateCriteria(typeof(News));
            if (!string.IsNullOrEmpty(title))
            {
                queryCount.Add(Restrictions.Like("Title", "%" + title + "%"));
                queryList.Add(Restrictions.Like("Title", "%" + title + "%"));
            }
            if (!string.IsNullOrEmpty(newsType))
            {
                queryCount.Add(Restrictions.Eq("NewsType", newsType));
                queryList.Add(Restrictions.Eq("NewsType", newsType));
            }
            if (startTime != null)
            {
                queryCount.Add(Restrictions.Gt("AddTime", startTime));
                queryList.Add(Restrictions.Gt("AddTime", startTime));
            }
            if (endTime != null)
            {
                queryCount.Add(Restrictions.Lt("AddTime", endTime));
                queryList.Add(Restrictions.Lt("AddTime", endTime));
            }
            dataCount = Convert.ToInt32(queryCount.SetProjection(Projections.Count("Id")).UniqueResult());
            return queryList.AddOrder(new Order("AddTime", false))
                .SetFirstResult(pageIndex * pageSize)
                .SetMaxResults(pageSize)
                .List<News>();
        }
    }
}
